package com.zhuoshi.demo;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.zhuoshi.bean.Orders;
import com.zhuoshi.bean.Person;
import com.zhuoshi.bean.QueryBean;

public class Demo1 {
	SqlSessionFactory factory;
	//每次调用 test方法的时候都会执行before
	@Before
	public void before() throws IOException{
		 InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
		 factory = new SqlSessionFactoryBuilder().build(is);
	}
	/**
	 * 一对多
	 */
	@Test
	public void oneToMany(){
		SqlSession openSession = factory.openSession();
		Person person = openSession.selectOne("com.zhuoshi.personMapper.selectByOneToMany", 6);
		System.out.println(person.getOrderList().size());
		openSession.close();
	}
	/**
	 * 一对多再对多
	 */
	@Test
	public void selectByOneToManyToMany(){
		SqlSession openSession = factory.openSession();
		Person person = openSession.selectOne("com.zhuoshi.personMapper.selectByOneToManyToMany", 5);
		System.out.println(person);
		openSession.close();
	}
	
	
	/**
	 *  多对一
	 */
	@Test
	public void selectByManyToOne(){
		SqlSession openSession = factory.openSession();
		Orders order = openSession.selectOne("com.zhuoshi.ordersMapper.selectByManyToOne", 2);
		System.out.println(order);
		openSession.close();
	}
	
	/**
	 *  需求： 根据订单获取 人 和 订单详情 
	 */
	@Test
	public void selectByManyToOneToMany(){
		SqlSession openSession = factory.openSession();
		Orders order = openSession.selectOne("com.zhuoshi.ordersMapper.selectByManyToOneToMany", 2);
		System.out.println(order);
		openSession.close();
	}
	
	/**
	 * 关联关系 多对多
	 */
	@Test
	public void selectManyToMany(){
		SqlSession openSession = factory.openSession();
		Person person = openSession.selectOne("com.zhuoshi.personMapper.selectManyToMany", 5);
		System.out.println(person);
		openSession.close();
	}
	
	/**
	 * 延迟加载 一对多
	 */
	@Test
	public void selectByLazyOne(){
		SqlSession openSession = factory.openSession();
		Person person = openSession.selectOne("com.zhuoshi.personMapper.selectByLazyOne", 5);
		System.out.println(person);
		System.out.println(person.getOrderList());
		openSession.close();
	}
	
	/**
	 * 延迟加载 多对一
	 */
	@Test
	public void selectByLazyMany(){
		SqlSession openSession = factory.openSession();
		Orders order = openSession.selectOne("com.zhuoshi.ordersMapper.selectByLazyMany", 1);
		System.out.println(order.getPerson());
		openSession.close();
	}
	
}
